package com.yupi.moshu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.moshu.common.BaseResponse;
import com.yupi.moshu.common.ErrorCode;
import com.yupi.moshu.common.ResultUtils;
import com.yupi.moshu.exception.BusinessException;

import com.yupi.moshu.model.domain.*;
import com.yupi.moshu.model.request.*;
import com.yupi.moshu.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

import static com.yupi.moshu.constant.UserConstant.ADMIN_ROLE;
import static com.yupi.moshu.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 * @author 7
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private EmailService emailService;

    @Resource
    private TeamUserService teamUserService;

    @Resource
    private TeamService teamService;

    @Resource
    private ProjectService projectService;

    @Value("${spring.mail.username}")
    private String from;

    @PostMapping(value = "/getEmailCode")
    public BaseResponse<Void> getEmailCode(@RequestBody CodeRequest codeRequest, HttpSession session) {
        emailService.sendEmail(codeRequest.getEmail(), session);
        return ResultUtils.success("验证码已发送");
    }

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest, HttpSession session) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String nickName = userRegisterRequest.getNickName();
        String realName = userRegisterRequest.getRealName();

        String userAccount = StringUtils.isEmpty(userRegisterRequest.getUserAccount()) ? userRegisterRequest.getEmail() : userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String code = userRegisterRequest.getCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "部分参数为空");
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword, code, nickName, realName, session);
        return ResultUtils.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    @PostMapping("/userInfo")
    public BaseResponse<User> getCurrentUser(@RequestBody ManageRequest manageRequest) {
        User user = userService.getById(manageRequest.getUserID());
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }

    @PostMapping("/teamList")
    public BaseResponse<List<Team>> teamList(@RequestBody ManageRequest manageRequest) {
        Long userID = manageRequest.getUserID();
        QueryWrapper<TeamUser> teamUserQueryWrapper = new QueryWrapper<>();
        teamUserQueryWrapper.eq("userID", userID);

        List<TeamUser> list = teamUserService.list(teamUserQueryWrapper);

        List<Team> retList = new ArrayList<>();
        for(TeamUser i : list) {
            Long teamID = i.getTeamID();
            retList.add(teamService.getById(teamID));
        }
        return ResultUtils.success(retList);
    }

    @PostMapping("/projectList")
    public BaseResponse<List<Project>> projectList(@RequestBody ManageRequest manageRequest) {
        Long userID = manageRequest.getUserID();
        QueryWrapper<TeamUser> teamUserQueryWrapper = new QueryWrapper<>();
        teamUserQueryWrapper.eq("userID", userID);

        List<TeamUser> list = teamUserService.list(teamUserQueryWrapper);

        List<Project> retList = new ArrayList<>();
        for(TeamUser i : list) {
            Long teamID = i.getTeamID();
            QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
            projectQueryWrapper.eq("teamID", teamID);
            List<Project> projectList = projectService.list(projectQueryWrapper);
            retList.addAll(projectList);
        }
        return ResultUtils.success(retList);
    }

    @PostMapping("/modify")
    public BaseResponse<Boolean> modify(@RequestBody ModifyRequest modifyRequest) {
        User user = userService.getById(modifyRequest.getUserID());
        user.setNickName(modifyRequest.getNickName());
        user.setRealName(modifyRequest.getRealName());
        user.setCity(modifyRequest.getCity());
        user.setEmail(modifyRequest.getEmail());
        user.setMotto(modifyRequest.getMotto());
        boolean result = userService.updateById(user);
        return ResultUtils.success(result);
    }

    @PostMapping("/avatarUpload")
    public BaseResponse<String> avatarUpload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "上传失败，请选择文件");
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件后缀名。也可以在这里添加判断语句，规定特定格式的图片才能上传，否则拒绝保存。
        assert fileName != null;
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //为了避免发生图片替换，这里使用了文件名重新生成
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-");
        String dateTime_s = dateTime.format(formatter);
        fileName = dateTime_s + UUID.randomUUID() + suffixName;

        //获取jar包所在目录
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
        //String uploadPath = jarF.getParentFile().toString()+"/classes/public/img/";
        String uploadPath = "/home/Pluviophile/web_project/backend/classes/public/img/";
        File saveFile = new File(uploadPath);
        if(!saveFile.exists()) {
            saveFile.mkdir();
        }

        //String path = ResourceUtils.getURL("classpath:").getPath()+"public/img/";
        file.transferTo(new File(uploadPath+fileName));

        String viewUrl = "http://124.221.200.179/api/img/"+fileName;

        return ResultUtils.success(viewUrl,"上传成功");
    }

    @PostMapping("/avatarModify")
    BaseResponse<Void> avatarModify(@RequestBody AvatarModifyRequest avatarModifyRequest) {
        Long userID = avatarModifyRequest.getUserID();
        String avatarUrl = avatarModifyRequest.getAvatarUrl();

        User user = userService.getById(userID);
        if (user == null) {
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "用户不存在");
        }
        user.setAvatarUrl(avatarUrl);
        userService.updateById(user);
        return ResultUtils.success("头像修改成功");
    }


    @PostMapping("/changePwd")
    public BaseResponse<Void> changePwd(@RequestBody ChangePwdRequest changePwdRequest) {
        Long userID = changePwdRequest.getUserID();
        String oldPwd = changePwdRequest.getOldPwd();
        String newPwd = changePwdRequest.getNewPwd();
        String checkPwd = changePwdRequest.getCheckPwd();

        userService.changePwd(userID, oldPwd, newPwd, checkPwd);
        return ResultUtils.success("修改密码成功，请重新登录");
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }
}
